<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                type="danger"
                icon="el-icon-delete"
                class="handle-del mr10"
                @click="delAllSelection"
                :disabled="isDisabled"
                >删除</el-button>
				<el-button
                    type="primary"
                    icon="el-icon-circle-plus-outline"
                    class="handle-del mr10"
                    @click="handleAdd"
                >添加</el-button>
                <el-input v-model="query.username" placeholder="请输入用户名称" class="handle-input mr10"></el-input>
                <el-button 
                    type="primary"
                    icon="el-icon-search"
                    class="handled-del mr10"
                    @click="handleSearch"
                >搜索</el-button>
                <el-button 
                    type="primary"
                    icon="el-icon-refresh"
                    class="handled-del mr10"
                    @click="Rest"
                >重置</el-button>
                 <el-select v-model="query.status" class="handle-select mr10" placeholder="用户状态" @change="statusChange">
                    <el-option
                    v-for="item in enableOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                <el-select v-model="query.classId" class="handle-select mr10" placeholder="班级" @change="classChange">
                    <el-option
                    v-for="item in classesOptinos"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                <el-select v-model="query.facultyId" class="handle-select mr10" placeholder="学院" @change="facultyChange">
                    <el-option
                    v-for="item in facultyOptinos"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
                 <!-- <el-date-picker
                    class="handle-date mr10"
                    v-model="date"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="dateChange"
                    value-format="yyyy-MM-dd">
                    </el-date-picker> -->
                <el-button
                    type="info"
                    icon="el-icon-download"
                    class="handled-del mr10"
                    @click="handleImport"
                >导入</el-button>
                <el-button
                    type="warning"
                    icon="el-icon-download"
                    class="handled-del mr10"
                    @click="handleExport"
                >导出</el-button>
            </div>
            <el-table
                v-loading="loading2"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0,0,0,0.8)"
                :data="tableList"
                border
                
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="userId" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="username" label="用户名" width="100" align="center"></el-table-column>
                <el-table-column prop="nickname" label="姓名" align="center" width="100"></el-table-column>
                <el-table-column prop="number" label="学号" align="center" width="120"></el-table-column>
                <el-table-column prop="gender" label="性别" align="center" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.gender===0" type="success">男</el-tag>
                        <el-tag v-else type="warning">女</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机" align="center" width="120"></el-table-column>
                <el-table-column prop="className" label="班级" width="200" align="center"></el-table-column>
                <el-table-column prop="facultyName" label="学院" width="200" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status===0" type="success">正常</el-tag>
                        <el-tag v-else type="danger">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="pass" label="不良记录" align="center" width="80">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.pass===0" type="success">无</el-tag>
                        <el-tag v-else type="danger">有</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" align="center">
                    <template slot-scope="scope">
                            <el-button
                            type="text"
                            icon="el-icon-success"
                            @click="handleReset(scope.$index, scope.row)"
                        >重置密码</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

<!--  添加编辑弹出框  -->

            <el-dialog :close-on-click-modal="false"
                :title="titleMap[dialogStatus]"
                :visible.sync="dialogFormVisible" width="35%">

            <el-form :model="form" :rules="rules" ref="form" label-width="70px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账号" prop="username" >
                            <el-input v-model="form.username"  @blur="checkUser" :disabled="unDisabled"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                     <el-form-item label="姓名" prop="nickname">
                         <el-input v-model="form.nickname"></el-input>
                     </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="form.password" :disabled="pwdDisabled"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="学号" prop="number">
                            <el-input v-model="form.number"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="form.phone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                            <el-select v-model="form.gender" placeholder="请选择">
                                <el-option
                                v-for="item in sexOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                
                 <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择">
                                <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                        <el-col :span="12">
                        <el-form-item label="班级" prop="classId">
                           <el-select v-model="form.classId" placeholder="请选择">
                                <el-option
                                v-for="item in classesOptinos"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="不良记录" prop="pass">
                            <el-select v-model="form.pass" placeholder="请选择">
                                <el-option
                                v-for="item in passOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

           </el-form>
            
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
            </span>
        </el-dialog>

        <!--  导入用户excel  -->
        <el-dialog
            title="用户导入"
            :visible.sync="excelVisible"
            width="35%"
            :before-close="excelClose"
            >
            <el-upload
                class="upload-demo"
                drag
                ref="excelUpload" 
                action="abc"
                :on-change="excelChange"
                :auto-upload="false"
                :multiple="false"
                :limit=1
                accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="" slot="tip"><el-link type="primary" @click="handleTemplate">模板下载</el-link></div>
                <div class="el-upload__tip" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelExcel">取 消</el-button>
                <el-button type="primary" @click="importExcel">确 定</el-button>
            </span>
            </el-dialog>
    </div>
    
</template>

<script>
import{selectAllFaculty} from "@/api/faculty.js";
import {deleteUser,deleteUsers,checkUsername,getUser,
        resetPwd,selectUserList,addUser,updateUser,getClassesInfo,exportUser,importUser} from "@/api/user.js";
import Qs from  'qs'

export default {
    name: 'user',
    data() {
        return {
            date: '',
            //查询参数
            query: {
                username:'',
                status:null,
                startDate:'',
                endDate:'',
                classId:null,
                facultyId:null,
                pageIndex: 1,
                pageSize: 10,
            },
            //新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
            titleMap: {
                add:'添加',
                edit: '编辑'
            },
            //用户文件
            userExcelFile:null,
            //上传文件dialog
            excelVisible:false,
            //判断是否为编辑操作，使用户名框不可修改
            unDisabled:false,
            //密码框是否禁用
            pwdDisabled:false,
            //新增和编辑弹框标题
            dialogStatus: "",
            // 遮罩层
            loading2: false,
            //表格数据
            tableData: [],

            //表格
            tableList:[],
            //
            flag:true,
            //班级列表
            classesOptinos:[],
            //学院信息
            facultyOptinos:[],

            // 用户状态
            statusOptions: [
                //{value: null,label: '请选择'},
                {value: '0',label: '正常'},
                {value: '1',label: '停用'},
            ],
            passOptions: [
                //{value: null,label: '请选择'},
                {value: '0',label: '无'},
                {value: '1',label: '有'},
            ],
            enableOptions: [
                {value: null,label: '状态'},
                {value: '0',label: '正常'},
                {value: '1',label: '停用'},
            ],
            // 用户性别
            sexOptions: [
                {value: '0',label: '男'}, 
                {value: '1',label: '女'}, 
            ],
            // 批量删除按钮是否可以点击
            isDisabled: true,

            // 存放批量删除用户
            multipleSelection: [],
            //编辑框是否显示
            dialogFormVisible:false,
            //列表总数
            pageTotal: 0,
            form: {
                userId:undefined,
                nickname:'',
                username:'',
                password:'',
                gender:'',
                number:null,
                //className:'',
                phone:'',
                status:'',
                pass:'',
                classId:'',
                facultyId:'',
            },
            //校验规则
            rules:{
                username: [{ required: true, message: '请填写账号', trigger: 'blur' }],
                nickname: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
                password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
                gender: [{ required: true,message: '请选择',trigger: 'blur' }],
                classId: [{ required: true, message: '请选择班级', trigger: 'blur' }],
                facultyId: [{ required: true, message: '请选择学院', trigger: 'blur' }],
                number: [{pattern: /^[0-9]*$/,required: true,message: '请填写学号(数字)',trigger: 'blur' }],
                status:[{required:true,message:'请选择',trigger:'blur'}],
                pass:[{required:true,message:'请选择',trigger:'blur'}],
                phone:[{pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}]
            },
        };
    },
    watch: {
        // 监听最后一页删除最后一条数据时，当前页不变情况
        pageTotal(){
            if(this.pageTotal==(this.query.pageIndex-1)*this.query.pageSize && this.pageTotal!=0){
                this.query.pageIndex-=1;
                this.getData();
            }
        }
    },
    created() {
        //获取数据列表
		this.getData()
        
    },
    mounted(){
        //获取班级信息
        this.getClasses();
        this.getFaculty();
    },
    methods: {
        getFaculty(){
            const _this = this;
            selectAllFaculty().then((res)=>{
                let classes = res.data;
                _this.facultyOptinos =  classes.map((item) => {
                    //组装，只需要id和name
                    return { value: item.facultyId,label: item.facultyName };
                });
            })
        },
        getClasses(){
            const _this = this;
            getClassesInfo().then((res)=>{
                let classes = res.data;
                _this.classesOptinos =  classes.map((item) => {
                    //组装，只需要id和name
                    return { value: item.classId,label: item.className };
                });
            })
        },

        
        submitForm(){
            const _this = this;
            //console.log(this.form);
            if(this.flag){
                this.$refs["form"].validate(valid=>{
                    if(valid){
                        let formData = new FormData();
                        formData.append('username',this.form.username)
                        formData.append('nickname',this.form.nickname)
                        formData.append('password',this.form.password)
                        formData.append('gender',this.form.gender)
                        formData.append('number',this.form.number)
                        formData.append('phone',this.form.phone)
                        formData.append('classId',this.form.classId)
                        formData.append('status',this.form.status)
                        formData.append('pass',this.form.pass)

                //编辑操作
                if(this.form.userId!=undefined){
                    formData.append('userId',this.form.userId)
                    updateUser(formData).then(res=>{
                        this.$message.success(res.message)
                        this.dialogFormVisible = false
                        this.getData()
                    })
                }
                //添加操作
                else{
                    addUser(formData).then(res=>{
                        //console.log(res)
                        this.$message.success(res.message);
                        this.dialogFormVisible = false;
                        this.getData();
                    })
                }
            }
            })
        }
        else{
            this.$message.error("该用户已存在！");
        }
            
        },

        Rest(){
            this.query.classId = null;
            this.query.facultyId = null;
            this.getData();
        },
        // 监听账号input 失去焦点事件
        checkUser(event){
        
            checkUsername(this.form.username).then((res)=>{
                //console.log(res)
                if(res.code === 400){
                    this.$message.error(res.message);
                    this.flag = false;
                }else{
                    this.flag = true;
                }
            }).catch(err=>{
                console.log(err)
            })
        },
        //添加操作
        handleAdd(){
            const _this = this
            this.resetForm();
            //显示弹框
            this.dialogFormVisible = true;
            //新增弹框标题
            this.dialogStatus = "add"
            this.unDisabled = false;
            this.pwdDisabled = false;

        },
        // 编辑操作
        handleEdit(index,row) {
            console.log(row);
            new Promise((resolve,reject)=>{
                this.resetForm();
                resolve();
            }).then(res=>{
                console.log(row);
                this.form = {...row};
                this.form.status ='' + row.status;
                this.form.gender ='' + row.gender;
                this.form.pass ='' + row.pass;
                // this.form.classId=''+row.classId;
            })
            .catch(err=>{
                console.log(err)
            })
            this.flag = true;
            this.dialogFormVisible = true;
            this.dialogStatus = "edit"
            this.unDisabled = true;
            this.pwdDisabled = true;
        }, 

        

		//获取列表数据
		  getData(){
            //console.log("page:"+this.query.page)
            const _this = this
            this.loading2 = true
            selectUserList(this.query).then((res)=>{
			    console.log(res)
			    _this.tableList = res.data.records;
                _this.pageTotal = res.data.total;
                // console.log(_this.pageTotal);
                // console.log(_this.pageSize);
            }).catch((err) => {
			        console.log('请求失败'+err)
			    });

            this.loading2 = false;
        },
        // 重置密码
        handleReset(index,row){
            this.$confirm('是否重置密码','提示',{
                type: 'warning'
            }).then(()=>{
                //console.log("id:"+row.userId);
                resetPwd(row.userId).then(res=>{
                    this.$message.success(res.message);
                })
            })
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index,row) {
            // 二次确认删除
            const _this = this
            const userId = row.userId
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                    Qs.stringify(userId)
                    console.log("userId:"+userId)
                    deleteUser(userId).then(res=>{
                        this.$message.success('删除成功');
                        _this.getData()
                    })
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            }).catch(err=>{
                console.log('删除失败'+err)
            })
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            if(this.multipleSelection.length === 0){
                this.isDisabled = true;
            }else{
                this.isDisabled = false;
            }
        },
        //搜索
        handleSearch(){
            this.$set(this.query,'pageIndex',1);
            this.getData();
        },
         // 用户导出excel
        handleExport(){
            this.$confirm('是否导出所有用户数据项','提示',{
                type: 'warning'
            }).then(()=>{
                exportUser().then(res => {
                    console.log("导出");
                    this.download(res.data);
                })
                
            }).catch(()=>{

            })
        },
        // 用户选择excel文件
        excelChange(file, fileList){
            this.userExcelFile = file.raw;
        },
        // 重置excel dialog
        resetExcel(){
            this.file = null;
            this.$refs.excelUpload.clearFiles();
        },
        //导入
        handleImport(){
            this.excelVisible = true;
         
        },
        //用户模板下载
        handleTemplate(){
            this.templateDownload('用户模板.xls');
        },
        // 取消excel dialog
        cancelExcel(){
            this.excelVisible = false;
            this.resetExcel();
        },
        // 右上角关闭excel
        excelClose(){
            this.excelVisible = false;
            this.resetExcel();
        },
        // 用户选择excel文件
        excelChange(file, fileList){
            this.userExcelFile = file.raw;
        },
        // 用户导入excel
        importExcel(){
            if(this.userExcelFile === null){
                this.$message.error('请选择文件')
            }else{
                this.$confirm('是否要导入用户数据','提示',{
                    type: 'warning'
                }).then(()=>{
                    let formData = new FormData();
                    formData.append('userExcelFile',this.userExcelFile);
                    importUser(formData).then(res => {
                        this.$message.success('导入成功');
                        this.getData();
                        this.excelVisible = false;
                        this.resetExcel();
                    })
                })
            }
        },
        // 重置excel dialog
        resetExcel(){
            this.userExcelFile = null;
            this.$refs.excelUpload.clearFiles();
        },
        // 班级下拉改变
        classChange(){
            this.getData();
        },
        // 学院下拉改变
        facultyChange(){
            this.getData();
        },
        // 用户状态下拉改变
        statusChange(){
            this.getData();
        },
        // 用户注册日期改变
        dateChange(){
            if(this.date != null){
                this.query.startDate = this.date[0];
                this.query.endDate = this.date[1];
            }else{
                 this.query.startDate = '';
                this.query.endDate = '';
            }
            this.getData();
        },
        
        //批量删除
        delAllSelection() {
            const _this = this;
            this.$confirm('确定要删除吗?','提示',{
                type: 'warning'
            }).then(()=>{
                const length = _this.multipleSelection.length;
                let ids = '';
                for(let i = 0;i<length-1;i++){
                     ids+=_this.multipleSelection[i].userId+','
                }
                ids += _this.multipleSelection[length-1].userId;
                deleteUsers(ids).then(res=>{
                _this.$message.success(res.message);
                _this.multipleSelection = [];
                _this.getData();
            }).catch(err=>{
                console.log("出错了"+err)
            })
            })
        },
        // 分页导航
        handlePageChange(pageIndex){
            this.query.pageIndex = pageIndex
            this.getData();
        },
        //表单重置
        resetForm(){

            this.form = {
                username: undefined,
                nickname: undefined,
                password: undefined,
                gender: null,
                number: undefined,
                phone: undefined,
                status: null,
                classId:undefined,
                pass:undefined,
                facultyId:undefined,
                //className: undefined,
            }
            this.$nextTick(()=>{
                this.$refs.form.resetFields();
            })
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
